package com.ruoyi.manufacturer.demo;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.base.domain.BaseDevice;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.manufacturer.ControlVo;
import com.ruoyi.manufacturer.MessageVo;
import com.ruoyi.manufacturer.common.CommonHandler;
import com.ruoyi.third.domain.ThirdMessage;
import com.ruoyi.third.domain.ThirdPlatform;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Date;

/**
 * 例子
 */
@Component
@Slf4j
public class DemoHandler extends CommonHandler {
    public static final String PF_CODE = "demo";
    private static Boolean running = false;
    @Override
    public String getPfCode() {
        return PF_CODE;
    }

    @Override
    public String getProtocol() {
        return PF_CODE;
    }

    @Override
    public AjaxResult control(ControlVo controlVo) {
        HttpUtils.sendPost("", JSONObject.toJSONString(controlVo));
        return AjaxResult.success();
    }

    @Override
    public MessageVo parseMessage(Object msg) {
        MessageVo messageVo = new MessageVo();
        messageVo.setTime(new Date());
        try{
            JSONObject root = JSONObject.parse(msg.toString());
            MessageVo.Device device = new MessageVo.Device();
            device.setCode(root.getString("code"));
            device.setName(root.getString("name"));
            device.setType(root.getString("type"));
            device.setModel(root.getString("model"));
            messageVo.setDevice(Collections.singletonList(device));

            messageVo.setType(ThirdMessage.TYPE_EVENT);

            MessageVo.Alarm alarm = new MessageVo.Alarm();
            alarm.setDeviceCode(root.getString("code"));
            alarm.setEventCode(root.getString("error"));
            alarm.setEventDesc(root.getString("msg"));
            messageVo.setAlarm(Collections.singletonList(alarm));
            return messageVo;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean start(ThirdPlatform platform) {
        running = true;
        log.info("插件 {} 启动成功", platform.getName());
        return running;
    }

    @Override
    public boolean stop(ThirdPlatform platform) {
        running = false;
        log.info("插件 {} 停止成功", platform.getName());
        return true;
    }

    @Override
    public boolean alive(ThirdPlatform platform) {
        return running;
    }

    @Override
    public void onAlarm(MessageVo.Alarm alarm, BaseDevice device) {

    }
}
